<?php
include './config/config.php';


$sql = "SELECT * FROM `pre_admin` WHERE `id` = '{$_GET['adminid']}'";
$data = query($sql);
$adminData = $data;

if ($_POST) {
  $id = $_POST['id'];

  $adminsql = "SELECT * FROM `pre_admin` WHERE `id` = '$id'";
  $adminData = query($adminsql);

  // ? 封装表单数据
  $formData = [
    'username' => $_POST['username']
  ];

  /**
   *  ! 1、如果只是上传图片，没有更新用户名和密码
   *  ! 2、更新用户名或者密码 没有更新图片
   *  ! 3、更新图片 需要旧的图片
   */
  // todo 用户名检查
  if ($_POST['action'] == 'check') {
    $val = $_POST['val'];

    $sql = "SELECT * FROM `pre_admin` WHERE `id` != '$id'";

    $checkData = queryAll($sql);

    foreach ($checkData as $item) {
      if ($val == $item['name']) {
        error("用户名已存在");
        break;
      }
    }
    success('用户名可以使用');
  }

  //  todo 检测文件是否上传
  if ($_FILES['avatar'] && $_FILES['avatar']['size'] > 0) {
    @delfile($adminData['avatar']);
    $avatar = upload("avatar");
    if ($avatar['code'] == 0) {
      ShowMsg($avatar['msg']);
      exit;
    } else {
      // ? 数据追加avatar
      $formData['avatar'] = $avatar['url'];
    }
  }

  // todo 检测是否修改密码
  if ($_POST['oldpass']) {
    if (empty($_POST['newpass']) || empty($_POST['repass'])) {
      ShowMsg("新密码或者旧密码不能为空");
      exit;
    }

    $pass = md5($_POST['oldpass'] . $adminData['salt']);
    if ($pass != $adminData['password']) {
      ShowMsg("旧密码不正确");
      exit;
    }
    if ($_POST['newpass'] != $_POST['repass']) {
      ShowMsg("新密码和旧密码输入不一致");
      exit;
    }

    $salt = build_ranstr();
    $formData['salt'] = $salt;
    $formData['password'] = md5($_POST['newpass'] . $salt);
  }


  $where = "`id` = '{$_POST['id']}'";
  $res = updataById("admin", $formData, $where);

  if ($res) {
    ShowMsg($res['msg'], "adminList.php");
  } else {
    ShowMsg("修改失败");
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include_once('common/meta.php'); ?>
</head>

<body>

  <?php include_once('common/header.php'); ?>

  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">修改管理员信息</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="adminList.php">AdminList</a> <span class="divider">/</span></li>
      <li class="active">Index</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='adminList.php'"><i class="icon-list"></i> 管理员列表</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form id="updata_form" method="POST" enctype="multipart/form-data">

                <input type="hidden" name="id" value="<?php echo $data['id']; ?>">

                <label>用户名</label>
                <input type="text" name="username" value="<?php echo $data['username']; ?>">
                <span id="username"></span>

                <label>旧密码</label>
                <input type="text" name="oldpass">

                <label>新密码</label>
                <input type="text" name="newpass">

                <label>确认密码</label>
                <input type="text" name="repass">

                <label for="avatar">头像</label>
                <input type="file" id="avatar" name="avatar" hidden>
                <label for="avatar">
                  <img src="<?php echo './upload/' . $data['avatar']; ?>" alt="" style='display:block;width:120px;height:120px;' id="img">
                </label>



                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>

  <script src="./assets/lib/jquery-1.8.1.min.js"></script>
  <script>
    // 图片预览函数
    function GetObjectURL(file) {
      // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
      var url = null;

      //判断是否为IE浏览器还是google还是其他浏览器
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file)
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file)
      }

      return url
    }

    $("#avatar").change(function() {
      let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};
      // console.log(file[0].files[0]);

      // return false;
      let url = GetObjectURL(file);
      $("#img").attr('src', url);
    });


    // todo 检测用户名
    $('input[name="username"]').change(function(e) {
      let val = $(this).val();
      let id = $("input[name='id']").val();
      $.ajax({
        type: "post",
        url: "adminUpdata.php",
        data: {
          id,
          val,
          action: 'check'
        },
        dataType: "json",
        success: function(res) {
          if (res.code === 1) {
            $("#username").html(res.msg).css({
              "color": "green"
            });
          } else if (res.code === 0) {
            $("#username").html(res.msg).css({
              "color": "red"
            });
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    })
  </script>
</body>

</html>
<?php include_once('common/script.php'); ?>